<?php

namespace App\Http\Middleware;

use App\Helpers\ApiResponse;
use App\Helpers\ResponseEnum;
use App\Models\BaseModel;
use App\Models\User;
use Closure;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;

class VerifyUserToken
{
    use ApiResponse;

    /**
     * 验证登录
     * @param $request
     * @param Closure $next
     * @return JsonResponse|mixed
     */
    public function handle(Request $request, Closure $next)
    {
        try {
            $token = $request->header('Authorization');
            if (empty($token)) {
                throw new Exception('未传token');
            }

            // 解析token
            if (!$user = JWTAuth::parseToken()->authenticate()) {
                throw new Exception('Token无效');
            }

            // 验证登录信息
            $user = User::query()->where('id', $user->id)->first();
            if (!$user) {
                throw new Exception('用户未注册');
            }
            if ($user->status != BaseModel::STATUS_ENABLE) {
                throw new Exception('用户有异常，请联系客服');
            }

            // 注入Request
            $request->uid = $user->id;

        } catch (Exception $e) {
            return $this->fail(ResponseEnum::CLIENT_HTTP_UNAUTHORIZED, $e->getMessage());
        }

        return $next($request);
    }
}
